import request from '@/utils/request';
import { requestWrapper, randomInt, randomPick, paginate, randomDate } from '@/utils/mock';

// 获取API文档列表
export function getApiDocList(params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/api-doc/list',
      method: 'get',
      params
    }),
    // 模拟数据
    () => {
      const pageNum = params?.pageNum || 1;
      const pageSize = params?.pageSize || 10;
      const total = 25; // 模拟总数
      
      const categories = ['auth', 'system', 'user', 'monitor', 'tool'];
      const statusOptions = ['0', '1']; // 0禁用 1启用
      const contentTypes = ['application/json', 'application/xml', 'text/html'];
      const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];
      
      // 生成文档数据
      const generateDoc = (index) => {
        const category = categories[randomInt(0, categories.length - 1)];
        const docId = index + 1;
        const status = randomPick(statusOptions);
        
        return {
          docId,
          name: `${category.charAt(0).toUpperCase() + category.slice(1)}接口文档${docId}`,
          description: `包含所有${category}相关接口`,
          url: `/api-docs/${category}`,
          method: methods[randomInt(0, methods.length - 1)],
          contentType: contentTypes[randomInt(0, contentTypes.length - 1)],
          status,
          createBy: 'admin',
          createTime: randomDate(-180),
          updateBy: randomInt(0, 1) ? 'admin' : null,
          updateTime: randomInt(0, 1) ? randomDate(-30) : null
        };
      };
      
      // 处理搜索条件
      let docs = Array.from({ length: total }, (_, i) => generateDoc(i));
      
      if (params) {
        if (params.name) {
          docs = docs.filter(item => item.name.includes(params.name));
        }
        
        if (params.status !== undefined && params.status !== '') {
          docs = docs.filter(item => item.status === params.status);
        }
      }
      
      // 处理分页
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = Math.min(startIndex + pageSize, docs.length);
      const list = docs.slice(startIndex, endIndex);
      
      return {
        list,
        total: docs.length,
        pageNum: parseInt(pageNum),
        pageSize: parseInt(pageSize)
      };
    }
  );
}

// 获取API文档详情
export function getApiDocDetail(docId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/tool/api-doc/${docId}`,
      method: 'get'
    }),
    // 模拟数据
    {
      docId: parseInt(docId),
      name: `API文档${docId}`,
      description: `这是API文档${docId}的详细描述信息`,
      url: `/api-docs/doc${docId}`,
      method: 'GET',
      contentType: 'application/json',
      content: `{
  "swagger": "2.0",
  "info": {
    "title": "API文档${docId}",
    "version": "1.0"
  },
  "paths": {
    "/api/v1/example": {
      "get": {
        "summary": "获取示例数据",
        "parameters": [],
        "responses": {
          "200": {
            "description": "成功"
          }
        }
      }
    }
  }
}`,
      status: '1',
      createBy: 'admin',
      createTime: randomDate(-180),
      updateBy: 'admin',
      updateTime: randomDate(-30)
    }
  );
}

// 新增API文档
export function addApiDoc(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/api-doc',
      method: 'post',
      data
    }),
    // 模拟数据
    {
      docId: randomInt(100, 999)
    }
  );
}

// 修改API文档
export function updateApiDoc(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/api-doc',
      method: 'put',
      data
    }),
    // 模拟数据
    null
  );
}

// 删除API文档
export function deleteApiDoc(docIds) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/tool/api-doc/${docIds}`,
      method: 'delete'
    }),
    // 模拟数据
    null
  );
}

// 获取API接口测试页面
export function getApiTest(docId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/system/api-doc/test/${docId}`,
      method: 'get'
    }),
    // 模拟数据
    {
      docId: parseInt(docId),
      name: `API文档${docId}`,
      description: `这是API文档${docId}的详细描述信息`,
      paths: [
        {
          path: `/example`,
          method: 'GET',
          summary: '获取示例数据',
          parameters: [],
          responses: {
            '200': {
              description: '成功',
              schema: {}
            }
          }
        },
        {
          path: `/example/{id}`,
          method: 'GET',
          summary: '获取示例详情',
          parameters: [
            {
              name: 'id',
              in: 'path',
              required: true,
              type: 'integer',
              description: '示例ID'
            }
          ],
          responses: {
            '200': {
              description: '成功',
              schema: {
                type: 'object',
                properties: {
                  id: { type: 'integer', description: 'ID' },
                  name: { type: 'string', description: '名称' },
                  value: { type: 'number', description: '值' }
                }
              }
            }
          }
        }
      ]
    }
  );
}

// 导入Swagger文档
export function importSwagger(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/system/api-doc/import-swagger',
      method: 'post',
      data
    }),
    // 模拟数据
    null
  );
}

// 导出API文档
export function exportApiDoc(docId, params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/tool/api-doc/export/${docId}`,
      method: 'get',
      params,
      responseType: 'blob' // 导出文件流
    }),
    // 模拟数据
    () => new Blob([`模拟API文档导出内容，ID: ${docId}`], { type: 'text/plain' })
  );
}

// 获取API分类
export function getApiCategories() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/api-doc/categories',
      method: 'get'
    }),
    // 模拟数据
    [
      { id: 'auth', name: '认证接口' },
      { id: 'system', name: '系统管理' },
      { id: 'tool', name: '系统工具' },
      { id: 'monitor', name: '系统监控' },
      { id: 'data', name: '数据分析' }
    ]
  );
}

// 更新API文档状态
export function updateApiDocStatus(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/system/api-doc/status`,
      method: 'put',
      data
    }),
    // 模拟数据
    null
  );
}

// 获取Swagger UI HTML
export function getSwaggerUiHtml() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/swagger-ui.html',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['<html><body><h1>Mock Swagger UI HTML</h1></body></html>'], { type: 'text/html' })
  );
}

// 获取Swagger配置
export function getSwaggerConfig() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/swagger-config',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['{}'], { type: 'application/json' })
  );
}

// 获取Swagger资源
export function getSwaggerResources() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/swagger-resources',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['[]'], { type: 'application/json' })
  );
}

// 获取v3 API文档
export function getV3ApiDocs() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/v3/api-docs',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['{}'], { type: 'application/json' })
  );
}

// 获取v3 API文档 YAML
export function getV3ApiDocsYaml() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/v3/api-docs.yaml',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['---'], { type: 'text/yaml' })
  );
}

// 获取v3 API文档 JSON格式
export function getV3ApiDocsJson() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/v3/api-docs.json',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['{}'], { type: 'application/json' })
  );
}

// 获取v3 API文档 XML格式
export function getV3ApiDocsXml() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/v3/api-docs.xml',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['<root></root>'], { type: 'text/xml' })
  );
}

// 获取v3 API文档 HTML格式
export function getV3ApiDocsHtml() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/v3/api-docs.html',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['<html><body><h1>API Docs</h1></body></html>'], { type: 'text/html' })
  );
}

// 获取v3 API文档 Markdown格式
export function getV3ApiDocsMd() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/v3/api-docs.md',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['# API文档\n## 接口列表\n...'], { type: 'text/markdown' })
  );
}

// 获取v3 API文档 Text格式
export function getV3ApiDocsTxt() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/v3/api-docs.txt',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['API文档文本格式...'], { type: 'text/plain' })
  );
}

// 获取v3 API文档 CSV格式
export function getV3ApiDocsCsv() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/tool/v3/api-docs.csv',
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['路径,方法,描述\n/user,GET,获取用户列表'], { type: 'text/csv' })
  );
}

// 导入API文档
export function importApiDoc(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/system/api-doc/import',
      method: 'post',
      data,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }),
    // 模拟数据
    { successCount: 1, failCount: 0, message: '导入成功' }
  );
} 